/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.dsms.common.util;


import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;

/**
 * jwt util
 */
@Component
@ConfigurationProperties(prefix = "jwt.config")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtUtil {

    private String key;

    private long ttl;

    private SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    /**
     * Get the converted private key object
     *
     */
    public SecretKey getSecretKey() {
        return Keys.hmacShaKeyFor(key.getBytes());
    }

    /**
     * generate JWT
     *
     * @param id user id
     * @param subject user
     * @param roles  role
     * @return jwt
     */
    public String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date nowDate = new Date(nowMillis);
        HashMap<String, Object> map = new HashMap<>(8);
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        JwtBuilder builder = Jwts.builder()
                                 .setHeaderParams(map)
                                 .setId(id)
                                 .setSubject(subject)
                                 .setIssuedAt(nowDate)
                                 .signWith(getSecretKey(), signatureAlgorithm)
                                 .claim("roles", roles);
        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl * 60 * 1000));
        }

        return builder.compact();
    }

    /**
     * parse JWT
     *
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr) {

        JwtParser build = Jwts.parserBuilder()
                              .setSigningKey(getSecretKey())
                              .build();
        Claims body = build.parseClaimsJws(jwtStr).getBody();

        return body;
    }

}
